package com.zzx.dao.imql;

import com.zzx.Util.DruidUtil;
import com.zzx.dao.BaseAdminDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @Author: Spider Man
 * @Description:
 * @Date Created in 2020-09-11 14:05
 * @Modified By:
 */
public class AdminDaoImp implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE eadmin set logintime=?,loginip=? where username=?";
    private static final String SQL_LOGIN_BY_USERNAME_AND_PASSWORD = "select id from eadmin where username=? and password=?";

    /**
     * 根据管理员的用户名更新时间和登录IP
     *
     * @param username 用户名
     * @param date 要更新的时间
     * @param ip 登录的ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            assert connection != null;
            preparedStatement = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            preparedStatement.setDate(1,new java.sql.Date(date.getTime()));
            preparedStatement.setString(2,ip);
            preparedStatement.setString(3,username);
            preparedStatement.execute();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.closeConnectionAndStatement(connection,preparedStatement);
        }
    }

    /**
     * 管理员凭借账号和密码登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录的结果，true表示成功，false表示失败
     */
    @Override
    public boolean login(String username, String password) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            assert connection != null;
            preparedStatement = connection.prepareStatement(SQL_LOGIN_BY_USERNAME_AND_PASSWORD);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            assert resultSet != null;
            DruidUtil.close(connection,preparedStatement,resultSet);
        }
        return false;
    }
}
